/**
 * Created by maiseries on 2018/1/10.
 */
import React from 'react';
import {
    StyleSheet,
    View,
    WebView,
    Image,
    TouchableOpacity
} from 'react-native';

import Constants from '../config/Constants'

let _self = null;

const baseUrl = Constants.DEV_MODE ? Constants.DEV_BASE_URL : Constants.BASE_URL;

export default class ServerWebView extends React.Component {

    static propTypes = {
        url: React.PropTypes.string,
        fullUrl: React.PropTypes.string
    };

    refresh() {
        _self.refs.webView.reload();
    }

    render() {
        _self = this;
        return (
            <WebView
                ref="webView"
                startInLoadingState={true}
                domStorageEnabled={true}//开启dom存贮
                javaScriptEnabled={true}//开启js
                mixedContentMode={'always'}
                renderLoading={() => {
                    return (
                        <View style={[base.rowCC, styles.loadingBox]}>
                            <Image
                                source={require('../sources/icon_global_loading.gif')}
                                resizeMode={'contain'}
                                style={styles.loading}/>
                        </View>
                    )
                }}
                renderError={() => {
                    return (
                        <View style={[base.rowCC, styles.loadingBox]}>
                            <TouchableOpacity
                                onPress={()=>this.refresh()}
                                activeOpacity={layout.TOUCH_OPACITY_ACTIVE}>
                                <Image
                                    style={styles.error}
                                    resizeMode={'contain'}
                                    source={require('../sources/image_webview_error.png')}/>
                            </TouchableOpacity>
                        </View>
                    )
                }}
                source={{uri: this.props.fullUrl ? this.props.fullUrl : baseUrl + this.props.url}}
                style={styles.webView}/>
        )
    }
}

const styles = StyleSheet.create({
    webView: {
        flex: 1,
        width: layout.MAX_WIDTH,
    },
    loadingBox: {
        flex: 1,
        width: layout.MAX_WIDTH,
        backgroundColor: '#fff'
    },
    loading: {
        width: layout.width(160),
        height: layout.height(160)
    },
    error: {
        width: layout.width(369),
        height: layout.height(247)
    },
});